<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <i class="el-icon-info" />
          <span>总记录条数: {{ total }} 条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="on1mport">导入excel</el-button>
          <el-button type="danger" size="small" @click="onExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="onAdd">新增员工</el-button>
        </template>
      </page-tools>
      <el-card>
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          :default-sort="{prop: 'workNumber'}"
        >
          <el-table-column
            type="index"
            width="55"
            label="序号"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="100"
          />
          <el-table-column
            label="头像"
            width="100"
          >
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" srcset=""> -->
              <imageHolder :url="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column
            prop="workNumber"
            label="工号"

            width="100"
          />
          <el-table-column

            prop="formOfEmployment"
            label="聘用形式 "
            width="150"
          >
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>

          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"

            width="150"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable
            width="180"
          />

          <el-table-column
            prop="address"
            label="操作"
            :formatter="formatter"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.native.prevent="deleteRow(scope.$index, scope.row)"
              >
                查看
              </el-button>
              <el-button
                type="text"
                size="small"
              >
                分配角色
              </el-button>
              <el-button
                type="text"
                size="small"
                @click.native.prevent="deleteItem(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-pagination
        :current-page="currentPage4"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="params.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <AddEmployee @close="handle" @submit="onSub" />
      </el-dialog>
      <!-- <el-dialog title="导入Excel" :visible.sync="showExelDialog">
        <UploadExcel />
      </el-dialog> -->
    </div>
  </div>
</template>
<script>
// import PageTools from '@/components/pageTools'
import { getEmployeesList, delEmployees } from '@/api/employees'
import AddEmployee from './addEmployee'
import EmployeeEnum from '@/constant/employees'
import imageHolder from '@/components/ImageHolder'
export default {
  components: {
    // PageTools
    AddEmployee, imageHolder
  },
  data() {
    return {
      loading: false,
      tableData: [],
      total: 1,
      currentPage4: 1,
      params: {
        page: 1,
        size: 5
      },
      showDialog: false,
      showExelDialog: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 导入Excel
    on1mport() {
      // this.showExelDialog = true
      this.$router.push('/import')
    },
    // 导出事件
    onExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // excel表示导入的模块对象
        console.log(excel)
        // excel.export_json_to_excel({
        //   header: ['姓名', '工资'], // 表头 必填
        //   data: [
        //     ['刘备', 100],
        //     ['关羽', 500]
        //   ], // 具体数据 必填
        //   filename: 'excel-list', // 文件名称
        //   autoWidth: true, // 宽度是否自适应
        //   bookType: 'xlsx' // 生成的文件类型
        // })
        // 1. 发请求，获取当前页的数据
        // const myres = await getEmployeesList(this.params)
        // console.log('请求回来的结果~~~~~~~~~~~~~', myres.data.rows)
        // 2. 修改一下数据格式，以便导出
        const { header, data } = this.transData(this.tableData)
        excel.export_json_to_excel({
          header, // 表头 必填
          data,
          filename: 'test-export-excel',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 导出处理数据
    transData(arr) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出数组中第一个元素，来根据key生成对应的中文
      const first = arr[0]
      const header = Object.keys(first).map(item => map[item])
      console.log('表头是', header)
      const data = arr.map(obj => {
        return Object.values(obj)
      })
      console.log('数据是', data)
      return { header, data }
    },
    // 格式化聘用形式字段
    formatEmployment(id) {
      const hireType = {}
      // const item = EmployeeEnum.hireType.find(item => item.id === id)
      // return item.value
      // return item
      EmployeeEnum.hireType.forEach(item => {
        hireType[item.id] = item.value
      })
      return hireType[id]
    },
    // 获取数据
    async getList() {
      this.loading = true
      const { data } = await getEmployeesList(this.params)
      console.log(data)
      this.total = data.data.total
      this.tableData = data.data.rows
      this.loading = false
    },
    // 删除
    async deleteItem(id, item) {
      try {
        const res = await delEmployees(item.id)
        console.log(res)
        this.$message.success(res.data.message)
        if (this.tableData.length === 1) {
          this.params.page--
          if (this.tableData.length === 0) {
            this.tableData.length = 1
          }
        }
      } catch (error) {
        console.log(error)
      }
      this.getList()
    },
    onAdd() {
      this.showDialog = true
    },
    // 关闭弹框
    handle() {
      this.showDialog = false
    },
    // 提交表单
    onSub() {
      this.showDialog = false
      this.getList()
    },
    // 查看员工详情
    deleteRow(ind, row) {
      console.log(ind, row)
      // this.$oruter.push('/employees/detail')
      this.$router.push('/employees/detail?id=' + row.id)
    },
    formatter(row, column) {
      return row.address
    },
    handleSizeChange(val) {
      console.log(val)
      this.params.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.params.page = val
      this.getList()
    }
  }
}
</script>
<style scoped>
::v-deep .el-card{
  margin-top: 25px !important;
}
</style>
